package de.fuberlin.inf.alp4.ue2;

import java.util.LinkedList;

public class Scheduler {
	
	private LinkedList<MethodRequest> list;	//TODO ActivationQueue statt List
	
	public Scheduler() {
		System.out.println("Initializing Scheduler");
		this.list = new LinkedList<MethodRequest>();
		System.out.println("Entering loop");
		this.loop();
	}
	
	public void loop() {
		//for(;;) {
			int v = 0;
			if(this.list.size() > v) {	//'cause no need to try to dispatch our queue if there's nothing inside
				System.out.println("trying to dispatch Item " + (v+1));
				if(this.list.get(0).guard())
					this.dispatch();	
				else {
					System.out.println("request guarded.");
					v++;
				}
			} else
				System.out.println("currently nothing to dequeue");
		//}
	}
	
	/**
	 * Puts the MethodRequest Object into the intern queue
	 * @param request a MethodRequest Object
	 * @return true - if the enqueue was successful, false - if not
	 */
	public boolean enqueue(MethodRequest request) {
		list.add(request);
		this.sortQueue(); //order queue by priority
		System.out.println("enqueued new MessageRequest - current list size: " + list.size());
		return list.get(list.size()-1).equals(request);
	}
	
	/**
	 * calls the first unguarded MethodRequest of the Queue
	 */
	public void dispatch() {
		System.out.println("request dequeued. Calling MethodRequest.");
		MethodRequest request = list.pollFirst();
		request.call();
	}
	
	/**
	 * sorts the Queue depending from the MethodRequest's Priority
	 * Aim: Anytimes the Queue is to be reorganized (like an addition of a new MethodRequest)
	 * the elements have to be resorted.
	 * Because most of the elements will always stay sorted when been sorted once, 
	 */
	private void sortQueue() {
		//TODO: Kinda nice sort algorithm
		
	}
}
